/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package appClient;

/**
 *
 * @author User
 */
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.simple.parser.ParseException;
import protocol.ClientProtocol;

public class ConnectClient extends Thread {
  private int port;
  private String login; 
  private String pass; 
  private String addr;
  private Socket socket;
  private BufferedReader in;
  private PrintWriter out;
  public javax.swing.JPanel FieldPannel;

 
  
  public ConnectClient(String login, String pass) throws IOException{
    this.port = port;
    this.login = login;
    this.pass = pass;
    this.addr = addr;
    addr = "localhost";
   // addr = "192.168.0.227";
    port = 8888;
    
    System.out.println("addr = " + addr);
    socket = new Socket(addr, port);
    System.out.println("socket = " + socket);
    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
    
    start();
    
  }
  
  
  
  public void refuse(String send){
     out.println(send);
  }

  
  public void run()
  {
      
    ClientProtocol cl = new ClientProtocol(this);
//      EventProducer ep = new EventProducer();
//      ep.addMyListener(new MyRealListener(this));
    
    try {

      out.println("{\"Type\":\"Connect\", \"Data\":\"" + login + "\", \"Add\":\"" + pass + "\"}");
      
      while (true)
            {
                String str = null;
        try {
          str = in.readLine();
        } catch (IOException ex) {
          Logger.getLogger(ConnectClient.class.getName()).log(Level.SEVERE, null, ex);
        }
                if (str.equals("{\"Type\": \"End\"}"))
                {
                  //out.println("{\"Type\": \"End\"}");
                  break;
                }
        try {
          // ep.getClient(str);
                 cl.getClient(str); /////////////
        } catch (ParseException ex) {
          Logger.getLogger(ConnectClient.class.getName()).log(Level.SEVERE, null, ex);
        }
       
                System.out.println("Client comming string: " + str);

            }
      
    } finally {
      System.out.println("closing ConnectClient ...");
      try {
        socket.close();
      } catch (IOException ex) {
        Logger.getLogger(ConnectClient.class.getName()).log(Level.SEVERE, null, ex);
      }
    }

  }
  
}
